package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Service
@Slf4j
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 条件查询
     *
     * @param addressBook
     * @return
     */
    public List<AddressBook> list(AddressBook addressBook) {
        return addressBookMapper.list(addressBook);
    }

    /**
     * 新增地址
     *
     * @param addressBook
     */
    public void save(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(0);
        addressBookMapper.insert(addressBook);
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    public AddressBook getById(Long id) {
        AddressBook addressBook = addressBookMapper.getById(id);
        return addressBook;
    }

    /**
     * 根据id修改地址
     *
     * @param addressBook
     */
    public void update(AddressBook addressBook) {
        addressBookMapper.update(addressBook);
    }

    /**
     * 设置默认地址
     *
     * @param addressBook
     */
    @Transactional
    public void setDefault(AddressBook addressBook) {
        // 【新增】首先，根据传入地址的ID，从数据库中查询出它的完整最新信息，特别是当前的 is_default 值
        AddressBook currentAddress = addressBookMapper.getById(addressBook.getId());

        // 判断：如果当前这条地址在数据库中已经是默认地址
        if (currentAddress.getIsDefault() == 1) {
            // 功能：点击后取消默认 -> 只需将本条地址设为非默认即可
            addressBook.setIsDefault(0);
            addressBookMapper.update(addressBook);
        } else {
            // 功能：点击后设为默认 -> 执行原来的两步操作
            // 1、将当前用户的所有地址修改为非默认地址
            // 注意：这里需要一个新的对象或方法来操作，避免影响后面的设置
            addressBookMapper.cancelAllDefault(BaseContext.getCurrentId());

            // 2、将当前地址改为默认地址
            addressBook.setIsDefault(1);
            addressBookMapper.update(addressBook);
        }
    }

    /**
     * 根据id删除地址
     *
     * @param id
     */
    public void deleteById(Long id) {
        addressBookMapper.deleteById(id);
    }

}
